import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author @fiber-cloud
 * @Date 2025/10/29 10:37
 */
//定义一个类，描述请求body内容
class Message{
    public String from ;
    public String to;
    public String message;
}


@WebServlet("/message")
public class MessageServlet extends HttpServlet {

    //使用这个list变量保存所有消息
    //private List<Message> messageList = new ArrayList<>();
    private ObjectMapper objectMapper = new ObjectMapper();

    //向服务器提交数据
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //把body中的内容读取出来，解析成一个Message对象
        Message message =objectMapper.readValue(req.getInputStream(),Message.class);

        //此处通过一个简单粗暴的方式进行保存操作
        //messageList.add(message);
        save(message);
        //此处设定状态码可以省略，不设置，默认值也是200
        resp.setStatus(200);
    }

    //从服务器获取数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //显式告诉浏览器，数据是json格式的，字符集是utf8
        resp.setContentType("application/json; charset=utf8");


//        //响应数据也是json格式
//        ObjectMapper objectMapper = new ObjectMapper();
//        // 往哪里写，写入的内容是啥
//        // writeValue方法可以把List格式的数据转换成json格式
//
//        objectMapper.writeValue(resp.getWriter(),messageList);


        //把Java对象转化成json字符串
        List<Message> messageList = load();
        String jsonResp = objectMapper.writeValueAsString(messageList);
        System.out.println("jsonResp："+ jsonResp);
        //把这个字符串写回到响应中
        resp.getWriter().write(jsonResp);
    }


    //提供一个方法 往数据库中写入消息
    private void save(Message message){
        //JDBC操作
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            // 建立连接
            connection = DBUtil.getConnection();
            //构造sql语句   要插入的是三个变量 需要占位符
            String sql = "insert into message values(?,?,?)";
            statement = (PreparedStatement) connection.prepareStatement(sql);

            statement.setString(1,message.from);
            statement.setString(2,message.to);
            statement.setString(3,message.message);
            //执行sql
            statement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭连接
            DBUtil.close(connection,statement,null);
        }
    }



    //从数据库取出所有消息
    private List<Message> load(){
        List<Message> messageList = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            //和数据库建立连接
            connection = DBUtil.getConnection();

            //构造sql语句
            String sql = "select * from message";

            statement = (PreparedStatement) connection.prepareStatement(sql);

            //执行sql
            resultSet = statement.executeQuery();

            while (resultSet.next()){
                Message message = new Message();

                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messageList.add(message);
            }

        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            //释放资源，断开连接
            DBUtil.close(connection,statement,resultSet);
        }
        return messageList;
    }
}
